package actor.remote.url

/**
 * Created by DJJ on 2019/12/24.
 */
package remoteLookup.remote
import actor.remote.url.Messages._
import akka.actor._
import akka.pattern._

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

class SupervisorActor extends Actor {
  def decider: PartialFunction[Throwable,SupervisorStrategy.Directive] = {
    case _: ArithmeticException => SupervisorStrategy.Resume
  }

  override def supervisorStrategy: SupervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 5 seconds){
      decider.orElse(SupervisorStrategy.defaultDecider)
    }

  val calcActor = context.actorOf(CalcProps.props,"calculator")

  override def receive: Receive = {
    case msg@ _ => calcActor.forward(msg)
  }

}

object CalculatorRunner extends App {

  val remoteSystem = ActorSystem("remoteSystem")
  val calcActor = remoteSystem.actorOf(Props[SupervisorActor],"supervisorActor")

  import remoteSystem.dispatcher

  calcActor ! Clear
  calcActor ! Num(13.0)
  calcActor ! Mul(1.5)

  implicit val timeout = akka.util.Timeout(1 second)

  private val future: Future[Any] = calcActor ? GetResult
  val reply = Await.result(future, timeout.duration).asInstanceOf[String]
  println("waiting")
  println(reply)
  println("I m here")
  scala.io.StdIn.readLine()

  calcActor ! Div(0.0)
  calcActor ! Div(1.5)
  calcActor ! Add(100.0)
  ((calcActor ? GetResult).mapTo[String]) foreach println
  scala.io.StdIn.readLine()

  remoteSystem.terminate()

}
